package net.xxcl.exam.service;

import java.util.Collections;
import java.util.List;

import jxl.Cell;
import net.xxcl.exam.mapper.*;
import net.xxcl.exam.pojo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional()
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private ScoreMapper scoreMapper;

    private static final Logger logger = LoggerFactory.getLogger(StudentService.class);

    @Transactional(readOnly = true)
    public int countByExample(Criteria example) {
        int count = this.studentMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    @Transactional(readOnly = true)
    public Student selectByPrimaryKey(Integer id) {
        return this.studentMapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public List<Student> selectByExample(Criteria example) {
        return this.studentMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer id) {
        return this.studentMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Student record) {
        return this.studentMapper.updateByPrimaryKeySelective(getSexByCardid(record));
    }

    public int updateByPrimaryKey(Student record) {
        return this.studentMapper.updateByPrimaryKey(getSexByCardid(record));
    }

    public int deleteByExample(Criteria example) {
        return this.studentMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(Student record, Criteria example) {
        return this.studentMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(Student record, Criteria example) {
        return this.studentMapper.updateByExample(record, example);
    }

    public int insert(Student record) {
        return this.studentMapper.insert(getSexByCardid(record));
    }

    public int insertSelective(Student record) {
        return this.studentMapper.insertSelective(getSexByCardid(record));
    }

    /**
     * 根据身份证号码判断性别
     * @param student
     * @return
     */
    @Transactional(readOnly = true)
    private Student getSexByCardid(Student student){
        if(student.getCardid()!=null){
            String cardid = student.getCardid();
            if(cardid.length()==18){
                //18位身份证取第17位判断，奇数为男，偶数为女
                student.setSex(Integer.parseInt(cardid.substring(16,17))%2);
            } else if(cardid.length()==15){
                //15位身份证取第14位判断，奇数为男，偶数为女
                student.setSex(Integer.parseInt(cardid.substring(14,15))%2);
            }
        }
        return  student;
    }

    /**
     * 登录验证
     * @param name
     * @param password
     * @return
     */
    @Transactional(readOnly = true)
    public Student login(String name,String password){
        Criteria criteria = new Criteria();
        criteria.put("cardid",name);
        criteria.put("password",password);
        List<Student> list = studentMapper.selectByExample(criteria);
        if (list.size()>0){
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @Transactional
    public int deletestudent(String ids) {
        String[] str = ids.split(",");
        for(String id:str){
            this.studentMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        return str.length;
    }

    /**
     * 重置密码
     * @param ids
     * @return
     */
    public int resetPass(String ids) {
        String[] str = ids.split(",");
        for(String id:str){
            Student student = studentMapper.selectByPrimaryKey(Integer.parseInt(id));
            String cardid = student.getCardid();
            student.setPassword(cardid.substring((cardid.length()-6),cardid.length()));
            StringBuffer question = new StringBuffer();
            question.append("[");
            this.studentMapper.updateByPrimaryKeySelective(student);
        }
        return str.length;
    }

    /**
     * 关联试卷
     * @param
     * @return
     */
    @Transactional
    public int glPaper(Integer stuid,Integer paperid) {
        try{
            Criteria criteria = new Criteria();
            Score score = new Score();
            score.setPaperid(paperid);
            score.setStuid(stuid);
            //表示已经关联过该试卷
            if(scoreMapper.selectByPrimaryKey(score)!=null){
                return 2;
            }
            StringBuffer question = new StringBuffer();
            question.append("[");
            for(int typeid = 1;typeid<=7;typeid++){
                criteria.clear();
                criteria.put("type",typeid);
                criteria.put("paperid",paperid);
                List<Integer> questionList = questionMapper.selectQuestionIdByExample(criteria);
                if(questionList.size()<=0){
                    continue;
                } else {
                    //打乱顺序
                    Collections.shuffle(questionList);
                    for(int i=0;i<questionList.size();i++){
                        question.append("{'id':");
                        question.append(questionList.get(i));
                        question.append(",answer:");
                        criteria.clear();
                        criteria.put("questionid",questionList.get(i));
                        List<Integer> answerList = answerMapper.selectAnswerIdByQuestionId(criteria);
                        if(answerList.size()<=0){
                            question.append("''},");
                        } else {
                            question.append("'");
                            //只有单选题和多选题才需要打乱答案的顺序
                            if(typeid==1 || typeid==2){
                                Collections.shuffle(answerList);
                            }
                            for(int j=0;j<answerList.size();j++){
                                question.append(answerList.get(j));
                                question.append(",");
                            }
                            question.append("'},");
                        }
                    }
                }
            }
            question.append("]");
            String questionStr = question.toString().replaceAll(",]","]");
            questionStr = questionStr.replaceAll(",'","'");
            score.setQuestion(questionStr);
            scoreMapper.insertSelective(score);
            return 1;
        } catch (RuntimeException e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 导入excel的一行记录
     * @param cells
     * @param paperId
     * @return
     */
    @Transactional()
    public Boolean saveExcelRow(Cell[] cells,int paperId){
        try{
            Criteria criteria = new Criteria();
            Student student = new Student();
            String cardid = cells[4].getContents().trim();
            criteria.put("cardid",cardid);
            //此处查询身份证号码是否已经存在，考虑改为查到即添加该身份证号，方便导入补考
            if(studentMapper.selectByExample(criteria).size()>0){
                throw new RuntimeException("身份证号码"+cardid+"已经存在");
            }
            student.setState(0);
            student.setCardid(cardid);
            //根据身份证设置性别
            student = getSexByCardid(student);
            student.setNumber(cells[0].getContents().trim());
            student.setUsername(cells[1].getContents().trim());
            student.setPhone(cells[5].getContents().trim());

            criteria.clear();
            criteria.put("blurredName",cells[3].getContents().trim());
            List<Tclass> classList = classMapper.selectByExample(criteria);
            //如果查询出有该班级，则设置为该班级，否则新插入班级
            if(classList.size()>0){
                student.setClassid(classList.get(0).getId());
            } else {
                // 若无该班级，则查询是否已有系部
                Tclass tclass = new Tclass();
                tclass.setName(cells[3].getContents().trim());
                criteria.clear();
                criteria.put("blurredName",cells[6].getContents().trim());
                classList = classMapper.selectByExample(criteria);
                //有系部，班级的上级指定为该系部
                if(classList.size()>0){
                    tclass.setParentid(classList.get(0).getId());
                } else {
                    //否则新建
                    Tclass xb = new Tclass();
                    xb.setName(cells[6].getContents().trim());
                    //指定上级为根节点
                    xb.setParentid(1);
                    classMapper.insert(xb);
                    tclass.setParentid(xb.getId());
                }
                classMapper.insert(tclass);
                student.setClassid(tclass.getId());
            }
            //截取身份证号码后6位作为密码
            student.setPassword(cardid.substring((cardid.length()-6),cardid.length()));
            studentMapper.insert(student);
            StringBuffer question = new StringBuffer();
            question.append("[");
            //关联考生和试卷的实体
            Score score = new Score();
            score.setPaperid(paperId);
            score.setStuid(student.getId());
            //打乱试题顺序和答案顺序，存到score表中，在关联试卷的时候即打乱，不在开始考试时打乱，提升性能
            for(int typeid = 1;typeid<=7;typeid++){
                criteria.clear();
                criteria.put("type",typeid);
                criteria.put("paperid",paperId);
                List<Integer> questionList = questionMapper.selectQuestionIdByExample(criteria);
                if(questionList.size()<=0){
                    continue;
                } else {
                    //打乱顺序
                    Collections.shuffle(questionList);
                    for(int i=0;i<questionList.size();i++){
                        question.append("{'id':");
                        question.append(questionList.get(i));
                        question.append(",answer:");
                        criteria.clear();
                        criteria.put("questionid",questionList.get(i));
                        List<Integer> answerList = answerMapper.selectAnswerIdByQuestionId(criteria);
                        if(answerList.size()<=0){
                            question.append("''},");
                        } else {
                            question.append("'");
                            //只有单选题和多选题才需要打乱答案的顺序
                            if(typeid==1 || typeid==2){
                                Collections.shuffle(answerList);
                            }
                            for(int j=0;j<answerList.size();j++){
                                question.append(answerList.get(j));
                                question.append(",");
                            }
                            question.append("'},");
                        }
                    }
                }
            }
            question.append("]");
            String questionStr = question.toString().replace(",]","]");
            questionStr = questionStr.replace(",'","'");
            score.setQuestion(questionStr);
            scoreMapper.insertSelective(score);
            return true;
        } catch (RuntimeException e){
            e.printStackTrace();
            throw e;
        }
    }
}